interface RequestOptions extends RequestInit {
  headers?: HeadersInit;
}

// 获取 token 的函数
const getToken = (): string => {
  return localStorage.getItem("token") || "";
};

export const request = async (url: string, options: RequestOptions = {}) => {
  // 每次请求时动态获取 token
  const token = getToken();

  // 合并请求头，但如果是 FormData 则不设置 Content-Type
  const headers: Record<string, string> = {
    Authorization: token,
  };

  // 如果不是 FormData，则设置 Content-Type
  if (!(options.body instanceof FormData)) {
    headers["Content-Type"] = "application/json";
  }

  // 合并用户自定义的请求头
  if (options.headers) {
    Object.assign(headers, options.headers);
  }

  // 发起请求
  try {
    const response = await fetch(url, {
      ...options,
      headers,
      credentials: "include", // 携带 cookie
    });

    // 解析响应
    const data = await response.json();

    // 处理响应
    console.log(response);
    if (response.ok) {
      return data;
    } else if (
      response.status === 401 &&
      response.statusText === "Unauthorized"
    ) {
      localStorage.removeItem("token");
      window.location.href = "/login";
    } else {
      throw new Error(data.message || "请求失败");
    }
  } catch (error) {
    console.error("请求失败:", error);
    throw error;
  }
};

// 封装常用请求方法
export const http = {
  get: (url: string, options?: RequestOptions) => {
    return request(url, { ...options, method: "GET" });
  },

  post: (url: string, data?: unknown, options?: RequestOptions) => {
    // 如果是 FormData，直接使用，否则转换为 JSON
    const body = data instanceof FormData ? data : JSON.stringify(data);

    return request(url, {
      ...options,
      method: "POST",
      body,
    });
  },

  put: (url: string, data?: unknown, options?: RequestOptions) => {
    return request(url, {
      ...options,
      method: "PUT",
      body: JSON.stringify(data),
    });
  },

  delete: (url: string, options?: RequestOptions) => {
    return request(url, { ...options, method: "DELETE" });
  },
};
